package be.kuleuven.peno3.mobiletoledo.view.multiplechoice;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import be.kuleuven.peno3.mobiletoledo.R;
import be.kuleuven.peno3.mobiletoledo.Data.Client.MultipleChoiceClient;
import be.kuleuven.peno3.mobiletoledo.model.Question;
import be.kuleuven.peno3.mobiletoledo.model.Result;
import be.kuleuven.peno3.mobiletoledo.model.User;

public class QuestionResult extends Activity {
	private TextView results, questiontxt;
	private Button delete, update;
	private int questionId;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.multiplechoicequestionresult);
		
		//questionid van de vraag waar we de resultaten van willen bekijken ophalen
		Bundle b = getIntent().getExtras();
		questionId = b.getInt("questionId");
		
		
		
		//tekstvelden koppelen aan variabelen om ze te kunnen manipuleren
		results=(TextView)findViewById(R.string.results);
		questiontxt=(TextView) findViewById(R.string.question);
		delete = (Button) findViewById(R.id.questionremovebutton);
		if(User.getInstance().isTeacher()) {
			delete.setVisibility(View.VISIBLE);
		}
		update = (Button) findViewById(R.id.questionupdateresultbutton);
		
		update.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				updateResult();
				Toast.makeText(QuestionResult.this, "De resultaten werden geupdated", Toast.LENGTH_SHORT).show();
			}
		});
		
		delete.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(User.getInstance().isTeacher()) {
					if(MultipleChoiceClient.deleteQuestion(QuestionResult.this.questionId)) {
						Toast.makeText(QuestionResult.this, "De vraag werd verwijderd", Toast.LENGTH_SHORT).show();
						QuestionResult.this.finish();
						return;
					}
					else {
						Toast.makeText(QuestionResult.this, "De vraag kon niet verwijderd worden", Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		
		updateResult();
	}
	
	private void updateResult() {
		//informatie over de resultaten en de vraag ophalen uit de database
		Question question = MultipleChoiceClient.getQuestion(questionId);
		Result result = MultipleChoiceClient.getResult(questionId);
		
		//tekstvelden instellen op de gewenste tekst
		try {
			questiontxt.setText(question.getContent());
			results.setText(result.calculateResult());
		}
		catch(NullPointerException ex) {
			ex.printStackTrace();
			Toast.makeText(this.getApplicationContext(), "Er is geen internetverbinding", Toast.LENGTH_SHORT).show();
			finish();
		}
	}
}
